package com.devops.admin.util;

import cn.hutool.core.util.StrUtil;
import com.devops.admin.model.DOSResource;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @ClassName JDBCTestUtil
 * @Description 测试数据库资源是否能够连接成功
 * @Author heyabo
 * @Date 2023/2/3 08:50
 * @Version 1.0
 **/
public class DatabaseConnectionTestUtil {

    public static boolean testConnection(DOSResource resource){

        // 首先判断一下资源的类型
        if (resource.getType().intValue() == 1) {
            return testDatabaseConnection(resource);
        } else if (resource.getType().intValue() == 3 && resource.getSubType().intValue() == 8){
            // redis
            return testRedisConnection(resource);
        }

        return false;
    }

    /**
     * @Author heyabo
     * @Description 测试数据库是否能够连接成功
     * @Date 09:08 2023/2/3
     * @Param [resource]
     * @return boolean
     **/
    private static boolean testDatabaseConnection(DOSResource resource) {
        //加载驱动类
        Connection conn = null;
        try {
            Class.forName(resource.getDriverName());
            conn = DriverManager.getConnection(resource.getUrl(),resource.getUsers(), resource.getPassword());
            if (conn.isClosed()){
                return false;
            } else {
                conn.close();
                return true;
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

    /**
     * @Author heyabo
     * @Description 测试redis是否能够连接成功
     * @Date 09:09 2023/2/3
     * @Param [resource]
     * @return boolean
     **/
    private static boolean testRedisConnection(DOSResource resource) {
        Jedis jedis = null;
        try {
            jedis = new Jedis(resource.getIp(),Integer.parseInt(resource.getPort()));
            if (StrUtil.isNotEmpty(resource.getUsers()) && StrUtil.isNotEmpty(resource.getPassword())){
                jedis.auth(resource.getUsers(), resource.getPassword());
            } else if (StrUtil.isNotEmpty(resource.getPassword())){
                jedis.auth(resource.getPassword());
            }
            String ping = jedis.ping();
            if (ping.equalsIgnoreCase("PONG")) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return false;
    }
}
